#include"head.h"

// ./Server 192.168.213.128 2222 3 
int main(int argc,char*argv[])
{
    //father process
    //check
    ARGS_CHECK(argc,4);
    //创建子进程 3
    WorkDate_t workAddr[10];
    int workNum = atoi(argv[3]);

    CreateWorker(atoi(argv[3]),workAddr);  //注意argv 需要字符串转换
    //建立tcp连接
    int sockfd;
    tcpInit(argv[1],argv[2],&sockfd);
    //把socket加入监听
    int epfd = epoll_create(10);
    epollAdd(epfd,sockfd);
    //准备好就绪数组
    for(int i=0;i<workNum;i++)
    {
        //建立管道
        epollAdd(epfd,workAddr[i].socketpair);
    }
    struct epoll_event readset[1024];
    while(1)
    {
        //epoll_wait
        int readyNum = epoll_wait(epfd,readset,1024,-1);//准备就绪，并且先不踢人
        //如果就绪
        for(int i=0;i<readyNum;i++)
        {
            if(readset[i].data.fd == sockfd)
            {
                int netfd = accept(sockfd,NULL,NULL);//暂时不接受客户端的ip和端口
                //判断子进程是否是空闲状态
                for(int j = 0;j < atoi(argv[3]);j++)
                {
                    //如果是空闲状态,像子进程发送netfd
                    if(workAddr[i].states == FREE)
                    {
                        printf("%d worker is free, pid = %d", j, workAddr[j].pid);
                        //像子进程发送netfd
                        sendfd(workAddr[j].socketpair,netfd);
                        workAddr[j].states = BUSY;
                        break;
                    }
                }
                //如果没有找到
                close(netfd);
            }
            else
            {
                for(int j = 0; j<workNum;j++)
                {
                    //子进程做完事情后，给父进程发消息
                    if(readset[i].data.fd == workAddr[j].socketpair)
                    {
                        pid_t pid;
                        read(readset[i].data.fd,&pid,sizeof(pid));
                        workAddr[j].states = FREE;
                        printf("%d worker is ready! pid = %d\n",j,pid);
                    }
                }
            }
        }
    }
    return 0;
    
}